import React, { memo, useEffect, useState } from 'react'
import {userIsLogin} from '../api/auth-api'
import Login from '../pages/Login'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { setUser } from '../store/modules/user'
import UserCenter from '../pages/UserCenter'
import { useLocation, useNavigate } from 'react-router-dom'
import { setRedirect } from '../store/modules/redirect'

const RouteProtect = memo(({children}) => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const [path, setPath] = useState(null)
    const location = useLocation()
    // const {isRedirect} = useSelector((state) => ({
    //     isRedirect: state.redirect.isRedirect
    // }), shallowEqual)
    // const _isRedirect = false

    useEffect(() => {
        console.log(location)
        if(!location.search) verify()
        else {
            location.search = ''
            setPath('children')}
    }, [location])

    const verify = async ()=>{
        try {
            // try里面是登录状态且token有效
            // 验证用户token 
            const res = await userIsLogin()
            const {message, ...user} = res
            dispatch(setUser(user))
            // 如果是要进入登录组件 则跳转到首页组件
            if(children.type === Login) setPath('home')
            // 其他组件可直接进入
            else setPath('children')
        } catch (res) {
            // catch 说明状态码不是200 进入axios的失败拦截器 返回的是失败promise 这里状态码为401
            // 未登录或者token过期 且进入的是usercenter界面直接跳转login
            if(res.status === 401 && children.type === UserCenter){
                setPath('login')
            }else{
                // 其他界面可以不用token可以进入
                setPath('children')
            }
        }
    }    
    // 这里逻辑有问题 好像是无限循环
    if(path === 'home') {
        location.search = 'navigate'
        return navigate('/')
    }
    if(path === 'login') {
        location.search = 'navigate'
        return navigate('/login')
    }
    if(path === 'children') {
        location.search = 'navigate'
        return children
    }else{
        return <div>正在验证 请骚等</div>
    }
     
})


export default RouteProtect